﻿using System;
using System.Data;
using System.Collections;
using System.Text.RegularExpressions;
using System.Text;
using System.Web.Caching;

using LTJ.Common;
using LTJ.Data;
using LTJ.Config;
using LTJ.Entity;
using LTJ.Common.Generic;
using LTJ.Cache;
using System.Web;

namespace LTJ.FrameWork
{
    /// <summary>
    /// 用户操作类
    /// </summary>
    public class Users
    {
        /// <summary>
        /// 创建新用户.
        /// </summary>
        /// <param name="__userinfo">用户信息</param>
        /// <returns>返回用户ID, 如果已存在该用户名则返回-1</returns>
        public static int CreateUser(UserInfo userinfo)
        {
            if (GetUserId(userinfo.lname) > 0)
                return -1;

            return LTJ.Data.DataProvider.Users.CreateUser(userinfo);
        }

        /// <summary>
        /// 根据用户名返回用户id
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>用户id</returns>
        public static int GetUserId(string username)
        {
            UserInfo userInfo = LTJ.Data.DataProvider.Users.GetUserInfoByName(username);
            return (userInfo != null) ? userInfo.id : 0;
        }

        /// <summary>
        /// 根据用户ID获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static UserInfo GetUser(int id)
        {
            return LTJ.Data.DataProvider.Users.GetUserInfo(id);
        }

        /// <summary>
        /// 获取用户分页数据
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public static DataTable GetUsersByPage(int pageindex, int pagesize, string condition, string orderstr)
        {
            return Data.DataProvider.Users.GetUsersByPage(pageindex, pagesize, condition, orderstr);
        }
        /// <summary>
        /// 根据用户所在公司和所在组获取用户数量
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="gid"></param>
        /// <returns></returns>
        public static int GetUsersByCidGid(int cid, int gid)
        {
            string sqlcon = "gid=" + gid + " AND cid=" + cid;
            if (gid == Convert.ToInt16(ManageGroup.NormalGroup)) sqlcon = "gid=" + gid + " AND scid=" + cid;

            return GetUsersCount(sqlcon);
        }

        /// <summary>
        /// 获取用户数量
        /// </summary>
        public static int GetUsersCount(string conditions)
        {
            return Data.DataProvider.Users.GetUsersCount(conditions);
        }

        public static bool UpdateUser(UserInfo uinfo)
        {
            return LTJ.Data.DataProvider.Users.UpdateUser(uinfo);
        }

        /// <summary>
        /// 判断指定用户密码是否正确.
        /// </summary>
        /// <param name="uid">用户ID</param>
        /// <param name="password">用户密码</param>
        /// <returns>如果用户密码正确则返回true, 否则返回false</returns>
        public static int CheckPassword(int uid, string password, bool originalpassword)
        {
            UserInfo userInfo = LTJ.Data.DataProvider.Users.CheckPassword(uid, password, originalpassword);

            return userInfo == null ? -1 : userInfo.id;
        }

        /// <summary>
        /// 检查密码
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="originalpassword">是否非MD5密码</param>
        /// <returns>如果正确则返回用户id, 否则返回-1</returns>
        public static int CheckPassword(string username, string password, bool originalpassword)
        {
            if (LTJ.Data.DataProvider.Users.GetUserInfoByName(username) == null)
            {
                return -2;
            }
            else
            {
                UserInfo userInfo = LTJ.Data.DataProvider.Users.CheckPassword(username, password, originalpassword);
                return userInfo == null ? -1 : userInfo.id;
            }
        }
        public static void WriteLoginCookie(UserInfo userinfo, int expires)
        {
            if (userinfo == null)
                return;

            HttpCookie cookie = new HttpCookie("dyj");
            cookie.Values["userid"] = userinfo.id.ToString();
            cookie.Values["username"] = userinfo.lname.ToString().Trim();
            cookie.Values["password"] = Utils.UrlEncode(userinfo.pass);
            //cookie.Values["usergroup"] = Utils.UrlEncode(LTJ.Entity.EnumType.GetCorpTypeName(Convert.ToInt16(LTJ.Entity.CorpType.CommonUser)));
            cookie.Values["usergroup"] = Utils.UrlEncode(LTJ.Entity.EnumType.GetCorpTypeName(userinfo.gid));
            cookie.Values["expires"] = expires.ToString();
            if (expires > 0)
            {
                cookie.Expires = DateTime.Now.AddMinutes(expires);
            }
            //string cookieDomain = GeneralConfigs.GetConfig().CookieDomain.Trim();
            //if (cookieDomain != string.Empty && HttpContext.Current.Request.Url.Host.IndexOf(cookieDomain.TrimStart('.')) > -1 && IsValidDomain(HttpContext.Current.Request.Url.Host))
            //{
            //    cookie.Domain = cookieDomain;
            //}

            HttpContext.Current.Response.AppendCookie(cookie);
        }
        /// <summary>
        /// 去除用户的用户组信息
        /// </summary>
        /// <param name="ids">用户id组合</param>
        /// <returns></returns>
        public static int RemoveUser(string ids,int gid)
        {
            return LTJ.Data.DataProvider.Users.RemoveUser(ids,gid);
        }

        public static int DelUser(string ids)
        {
            return LTJ.Data.DataProvider.Users.DelUser(ids);
        }

        /// <summary>
        /// 企业管理员查询条件组合
        /// </summary>
        /// <param name="cid">企业ID</param>
        /// <param name="sname">用户名</param>
        /// <param name="ename">英文名</param>
        /// <param name="rname">真实名</param>
        public static string GetCorpManagerCondation(int cid, string sname, string ename, string rname, bool isVaild)
        {
            string strWhere = " gid = " + Convert.ToInt16(ManageGroup.CorpGroup) + " ";

            if (isVaild) strWhere += " AND status = 1 ";
            if (!string.IsNullOrEmpty(sname)) strWhere += " AND lname like '%" + sname + "%' ";
            if (!string.IsNullOrEmpty(ename)) strWhere += " AND ename like '%" + ename + "%' ";
            if (!string.IsNullOrEmpty(rname)) strWhere += " AND rname like '%" + rname + "%' ";
            if (cid > 0) strWhere += " AND cid = " + cid;

            return strWhere;
        }

        /// <summary>
        /// 企业管理员查询条件组合
        /// </summary>
        /// <param name="sname">用户名</param>
        /// <param name="ename">英文名</param>
        /// <param name="rname">真实名</param>
        /// <param name="isVaild">是否判断可用状态</param>
        public static string GetCorpManagerCondation(string sname, string ename, string rname, bool isVaild)
        {
            string strWhere = " gid = " + Convert.ToInt16(ManageGroup.CorpGroup) + " ";

            if (isVaild) strWhere += " AND status = 1 ";
            if (!string.IsNullOrEmpty(sname)) strWhere += " AND lname like '%" + sname + "%' ";
            if (!string.IsNullOrEmpty(ename)) strWhere += " AND ename like '%" + ename + "%' ";
            if (!string.IsNullOrEmpty(rname)) strWhere += " AND rname like '%" + rname + "%' ";

            return strWhere;
        }
        /// <summary>
        /// 企业用户查询条件组合
        /// </summary>
        public static string GetCorpUserCondationByCid(int cid, string sname, string ename, string rname)
        {
            return GetCorpUserCondationByCid(cid, sname, ename, rname, 0, 0);
        }
        /// <summary>
        /// 企业用户查询条件组合
        /// </summary>
        public static string GetCorpUserCondationByCid(int cid, string sname, string ename, string rname, int noinfid, int infid)
        {
            string strWhere = " gid = " + Convert.ToInt16(ManageGroup.NormalGroup) + " AND scid = " + cid;

            if (!string.IsNullOrEmpty(sname)) strWhere += " AND lname like '%" + sname + "%' ";
            if (!string.IsNullOrEmpty(ename)) strWhere += " AND ename like '%" + ename + "%' ";
            if (!string.IsNullOrEmpty(rname)) strWhere += " AND rname like '%" + rname + "%' ";

            if (noinfid > 0) strWhere += " AND fid = 0 AND fid <> " + noinfid;
            else if (infid > 0) strWhere += " AND fid = " + infid;

            return strWhere;
        }

        /// <summary>
        /// 企业用户选择查询条件组合
        /// </summary>
        public static string GetCorpUserCondationByFid(int cid, int uid, string sname, string ename, string rname, string epinfid)
        {
            string strWhere = " gid = " + Convert.ToInt16(ManageGroup.NormalGroup) + " AND scid = " + cid;

            if (uid > 0) strWhere += " AND fid = " + uid;

            if (!string.IsNullOrEmpty(sname)) strWhere += " AND lname like '%" + sname + "%' ";
            if (!string.IsNullOrEmpty(ename)) strWhere += " AND ename like '%" + ename + "%' ";
            if (!string.IsNullOrEmpty(rname)) strWhere += " AND rname like '%" + rname + "%' ";

            if (!string.IsNullOrEmpty(epinfid)) strWhere += " AND id NOT IN (" + epinfid + ")";

            return strWhere;
        }

        /// <summary>
        /// 暂停用户
        /// </summary>
        public static bool PauseUsers(string ids)
        {
            return UpdateUserStatus(ids, 0);
        }

        /// <summary>
        /// 启用用户
        /// </summary>
        public static bool StartUsers(string ids)
        {
            return UpdateUserStatus(ids, 1);
        }

        /// <summary>
        /// 更新用户状态信息
        /// </summary>
        public static bool UpdateUserStatus(string ids, int status)
        {
            return LTJ.Data.DataProvider.Users.UpdateUserStatus(ids, status);
        }

        /// <summary>
        /// 更新用户所属管理员ID
        /// </summary>
        /// <param name="uid">用户ID</param>
        /// <param name="fid">管理员ID</param>
        public static bool UpdateUserFid(int uid, int fid)
        {
            return Data.DataProvider.Users.UpdateUserFid(uid, fid);
        }
        /// <summary>
        /// 批量更新用户所属管理员ID
        /// </summary>
        public static bool UpdateUsersFid(int fid, string ids)
        {
            return Data.DataProvider.Users.UpdateUsersFid(fid, ids);
        }

        /// <summary>
        /// 设置企业管理员权限
        /// </summary>
        /// <param name="cid">企业ID</param>
        /// <param name="uid">用户ID</param>
        /// <param name="iscreater">是否超级管理员</param>
        /// <param name="authorities">权限集合</param>
        /// <returns>更新是否成功</returns>
        public static bool SetCorpManagerAuth(int cid, int uid, bool iscreater, string authorities)
        {
            if (cid <= 0 || uid <= 0) return false;
            SASCache.GetCacheService().RemoveObject("/LTJ/userauths_" + uid);
            return LTJ.Data.DataProvider.Users.SetCorpManagerAuth(cid, uid, iscreater, authorities);
        }

        /// <summary>
        /// 获取权限实体
        /// </summary>
        /// <param name="cid">企业ID</param>
        /// <param name="uid">用户ID</param>
        /// <returns>权限实体</returns>
        public static Authority GetAuthInfo(int cid, int uid)
        {
            return LTJ.Data.DataProvider.Users.GetAuthInfo(cid, uid);
        }

        /// <summary>
        /// 获取用户缓存权限信息
        /// </summary>
        public static Authority GetAuthInfoCache(int cid, int uid)
        {
            return GetAuthListByUid(uid).Find(new Predicate<Authority>(delegate(Authority auinfo) { return auinfo.Cid == cid; }));
        }

        /// <summary>
        /// 获取企业管理员权限
        /// </summary>
        public static DataTable GetCorpManagerAuthList(int pageindex, int pagesize, string condition)
        {
            return LTJ.Data.DataProvider.Users.GetCorpManagerAuthList(pageindex, pagesize, condition);
        }

        /// <summary>
        /// 根据条件企业管理员数量
        /// </summary>
        public static int GetCorpManagerAuthCount(string condition)
        {
            return LTJ.Data.DataProvider.Users.GetCorpManagerAuthCount(condition);
        }

        /// <summary>
        /// 根据条件获取企业管理员查询条件
        /// </summary>
        public static string GetCorpManagerCondition(string keyvalue)
        {
            string conditions = " gid = " + Convert.ToInt16(ManageGroup.CorpGroup) + " ";

            if (keyvalue != "") conditions += " AND (lname LIKE '%" + keyvalue + "%' OR rname LIKE '%" + keyvalue + "%' OR ename LIKE '%" + keyvalue + "%')";

            return conditions;
        }

        /// <summary>
        /// 批量删除企业管理员
        /// </summary>
        public static void DeleteCorpManagerAuth(string idsparm)
        {
            Regex rx = new Regex(@"\|+(\d)+\,");
            MatchCollection m = rx.Matches(idsparm);
            foreach (Match sm in m)
            {
                SASCache.GetCacheService().RemoveObject("/LTJ/userauths_" + sm.Groups[1].Value);
            }

            LTJ.Data.DataProvider.Users.DeleteCorpManagerAuth(idsparm);
        }

        /// <summary>
        /// 根据用户ID获取用户权限列表
        /// </summary>
        public static List<Authority> GetAuthListByUid(int uid)
        {
            List<Authority> authlist = new List<Authority>();
            authlist = SASCache.GetCacheService().RetrieveObject("/LTJ/userauths_" + uid) as List<Authority>;

            if (authlist == null)
            {
                authlist = LTJ.Data.DataProvider.Users.GetAuthListByUid(uid);
                SASCache.GetCacheService().AddObject("/LTJ/userauths_" + uid, authlist);
            }

            return authlist;
        }
    }
}
